<template>
  <div class="changpassword">
    <nav-bar
      class="user-changeInfo"
      title="个人信息"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
    >
      <template #right>
        <icon name="ellipsis" size="18" />
      </template>
    </nav-bar>

    <Form @submit="onSubmit">
      <cell-group inset>
        <field
          v-model="oldPassword"
          name="oldPassword"
          label="原密码"
          placeholder="原来密码"
          :rules="[{ required: true, message: '请填写原密码' }]"
        />
        <field
          v-model="password"
          type="password"
          name="password"
          label="新密码"
          placeholder="新密码"
          :rules="[{ required: true, message: '请填写新密码' }]"
        />
      </cell-group>
      <div style="margin: 16px">
        <Button round block type="primary" native-type="submit"
          >确认修改密码</Button
        >
      </div>
    </Form>
  </div>
</template>
<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { Form, Field, CellGroup, NavBar, Toast, Icon, Button } from "vant";
import { useInfoAPI, passwordAPI } from "../../services/auth";
const { push } = useRouter();
const onClickLeft = () => {
  push({
    name: "user",
  });
};
const onClickRight = () => Toast("加入");
const oldPassword = ref("");
const password = ref("");
const pwd2 = ref("");
// 获取原先密码
useInfoAPI().then((res) => {
  if (res.code === 1) {
    pwd2.value = res.data.password;
  }
});
const onSubmit = (values) => {
  // console.log(values);
  if (values.oldPassword === pwd2.value) {
    if (values.password === values.oldPassword) {
      Toast.fail("两次密码一样");
    } else {
      passwordAPI({
        password: values.password,
        oldPassword: values.oldPassword,
      }).then((res) => {
        Toast.success(res.data);
        setTimeout(() => {
          push({
            name: "user",
          });
        }, 2000);
      });
      // values.pswd = "";
      // values.pwd = "";
    }
  } else {
    Toast.fail("原密码错误");
  }
};
</script>
